package Context
{
    import flash.filesystem.File;
    
    import mx.collections.ArrayCollection;
    
//    const UNDO_STACK_FILE_NAME:String = "UNDO_STACK";
        
    public class UndoStack extends ArrayCollection
    {
        public const MAX_STACK_LENGTH:int = 500;
        
        private var _maxid:int;
        private var _maxeventid:int;
        
        private var _projdir:File;
        
        public function UndoStack(projdir:File)
        {
            _projdir = projdir;
        }
        
        public function popItem():UndoItem {
            if(this.length == 0) {
                return null;
            }
            var item:UndoItem = this.getItemAt(0) as UndoItem;
            this.removeItemAt(0);
            return item;
        }
        
        public function popEvent():ArrayCollection {
            if(this.length == 0) {
                return null;
            }
            var ac:ArrayCollection = new ArrayCollection();
            
            var eid:int = this[0].eventId;
            for( ; ; ) {
                var ui:UndoItem = this.getItemAt(0) as UndoItem;
                if(ui.eventId && ui.eventId !== eid) {
                    break;
                }
                ac.addItem(ui);
                this.removeItemAt(0);
            }
            return ac;
        }
        
        private function get nextItemId():int {
            return ++this._maxid;
        }
        
        private function get nextEventId():int {
            return ++this._maxeventid;
        }
        
        public function pushItem(ifname:String, text:String, 
                        eventid:int = 0, 
                        beginsel:int = 0, endsel:int = 0):int {
            if(eventid == 0) {
                eventid = nextEventId;
            }
            var itemid:int = nextItemId;
            var ui:UndoItem = new UndoItem(ifname, text, eventid, itemid, beginsel, endsel); 
            this.addItem(ui);
            if(MAX_STACK_LENGTH < this.length) {
                this.removeItemAt(this.length - 1);
            }
            return itemid;
        }
    }        
}